local skynet = require "skynet"
require "skynet.manager"

local loglevel = {
	debug = 0,
	info = 1,
	warn = 2,
	error = 3,
}

local logger = {
	_level = 0,
}

local CMD = {}

function CMD.set_log_level(level)
	local val = loglevel.debug

	if level and loglevel[level] then
		val = loglevel[level]
	end

	logger._level = val
end

local function formatmsg(loglevel,name,label)
	-- print(loglevel,name,label)
	local datetime = os.date("%m-%d %H:%M:%S")
	local msg = string.format("[%s] [%s] [%s] %s", datetime,loglevel,name,label)
	return msg
end

function CMD.debug(name,label,...)
	if logger._level <= loglevel.debug then
		local msg = formatmsg("debug",name,label)

		skynet.error(msg,...)
	end
end

function CMD.info(name,label,...)
	if logger._level <= loglevel.info then
		local msg = formatmsg("info",name,label)

		skynet.error(msg,...)
	end
end

function CMD.warn(name,label,...)
	if logger._level <= loglevel.warn then
		local msg = formatmsg("warn",name,label)
		skynet.error(msg,...)
	end
end

function CMD.error(name,label, ...)
	if logger._level <= loglevel.error then
		local msg = formatmsg("error",name,label)

		skynet.error(msg,...)
	end
end

function CMD.init()
	
end

skynet.start(function()
	if not logger._level then
		local level = skynet.getenv "log_level"
		
		local default_level = loglevel.debug
		local val

		if not level or not loglevel[level] then
			val = default_level
		else
			val = loglevel[level]
		end

		logger._level = val
	end

	skynet.dispatch("lua", function(session, source, cmd, ...)
		local f = assert(CMD[cmd], cmd .. "not found")
		if cmd == "start" or cmd == "stop" then
			skynet.retpack(f(...))
		else
			f(...)
		end
	end)

	skynet.register(SERVICE_NAME)
end)
